package graph;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

public abstract class GraphBuilder<T,V> {
	static abstract class StringSource {
		abstract String get();
	}
	class ReaderStringSource extends StringSource {
		private BufferedReader is;
		ReaderStringSource(BufferedReader i) {
			is = i;
		}
		@Override
		String get() {
			try {
				return is.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		
	}
	class StringStringSource extends StringSource {
		private String string;
		StringStringSource(String s) {
			string = s;
		}
		@Override
		String get() {
			String result = string;
			string = null;
			return result;
		}
		
	}
	protected ArrayList<Node<T>> nodes = new ArrayList<Node<T>>();
	protected ArrayList<Edge<T,V>> edges = new ArrayList<Edge<T,V>>();

	public final Graph<T,V> build(String s) {
		return process(new StringStringSource(s));
	}


	public final Graph<T,V> build(Reader r) {
		return build(new BufferedReader(r)); 
	}

	public final Graph<T,V> build(BufferedReader r) {
		return process(new ReaderStringSource(r));
	}
	
	private Graph<T,V> process(StringSource source) {
		while (true){
			String line = source.get();
			if (line == null) break;
			process(line);
		}
		return new Graph<T,V>(nodes, edges);
	}

	protected abstract void process(String line);

}
